package Model;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.JsonReader;

public class Appoinment {
	public final Integer appoinmentID;
	public final Date startingDate;
	public final Date endingDate;
	public final Restaurant restaurant;
	public Appoinment(String s) throws ParseException {
		Date start = new Date(), end = new Date();	Integer aID = -1;	Restaurant r = null;
		try {
			JSONObject obj = new JSONObject(s);
			Iterator it = obj.keys();
			while (it.hasNext()) {
				String key = ((String)it.next());
				if ("Time".equalsIgnoreCase(key)) {
					String text = obj.getString(key);
					DateFormat df = DateFormat.getDateTimeInstance();
					start = df.parse(text);
				} else if ("restaurant".equalsIgnoreCase(key)) {
					long rid = obj.getLong(key);
					r = new Restaurant(rid);
				} else if ("idAppoinment".equalsIgnoreCase(key)) {
					aID = obj.getInt(key);
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		startingDate = start;
		endingDate = end;
		appoinmentID = aID;
		restaurant = r;
	}
	final static String cancelAppoinmentAddress = "http://happywaiman.dlinkddns.com/Reserve/User/Appoinment.php?action=delete&aid=_aid&uid=_uid&cid=_cid";
	public void cancelAppoinment() {
		LoginModel model = LoginModel.shareModel;
		String addr = cancelAppoinmentAddress.replaceAll("_aid", appoinmentID.toString());
		String content = model.query(addr);
	}
	final static String fetchAppoinmentAddr = "http://happywaiman.dlinkddns.com/Reserve/User/Appoinment.php?action=display&uid=_uid&cid=_cid";
	public static Appoinment[] fetchAllAppoinments() throws JSONException, ParseException {
		String content = LoginModel.shareModel.query(fetchAppoinmentAddr);
		JSONArray jsArray = new JSONArray(content);
		Appoinment[] app = new Appoinment[jsArray.length()];
		for (int i = 0; i < jsArray.length(); i++) {
			app[i] = new Appoinment(jsArray.getString(i));
		}
		return app;
	}
}